package com.cn.kehong.service;

import com.cn.kehong.api.ILaborAttendRecordService;
import com.cn.kehong.api.ILaborRateService;
import com.cn.kehong.conf.Config;
import com.cn.kehong.dao.LaborRateMapper;
import com.cn.kehong.domain.*;
import com.cn.kehong.utils.CommonUtil;
import com.cn.kehong.utils.Constants;
import com.cn.kehong.utils.QueryForm;
import com.cn.kehong.utils.TemplateExcelUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LaborRateServiceImpl implements ILaborRateService {
    @Autowired
    private LaborRateMapper laborRateMapper ;

    @Autowired
    private ILaborAttendRecordService laborAttendRecordService;
    @Autowired
    private Config config;
    @Override
    public List<LaborRate> getLaborRateLists(QueryForm queryForm) throws Exception {
        int count = laborRateMapper.selectLaborListsCount(queryForm);
        if(count == 0){
            return Lists.newArrayList();
        }
        List<LaborRate> laborRates = laborRateMapper.selectLaborLists(queryForm);
        laborRates.get(0).setCount(count);
        return laborRates;
    }

    @Override
    public List<LaborRate> getLaborRateListsByTimeAndFactoryName(QueryForm queryForm) throws Exception {
        String labTime = queryForm.getLaborTime();
        String factoryName = queryForm.getFactoryName();
        if(StringUtils.isEmpty(labTime)||StringUtils.isEmpty(factoryName)){
            return Lists.newArrayList();
        }
        LaborRateExample example = new LaborRateExample();
        example.createCriteria().andFactoryNameEqualTo(factoryName).andLaborTimeLike(labTime+"-%").andStatusEqualTo(Constants.NORMAL_STATUS).andLabStatusEqualTo("1");
        example.setOrderByClause("labor_time asc");
        List<LaborRate> laborRates = laborRateMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(laborRates)){
            return laborRates;
        }
        return laborRates;
    }


    @Override
    public String addLaborRate(LaborRate laborRate) throws Exception{
        LaborAttendRecord laborAttendRecord = laborRate.getLaborAttendRecord();
        if(null == laborAttendRecord){
            return "参数异常！";
        }
        List<LaborAttendDetail> laborAttendDetails = laborAttendRecord.getLaborAttendDetails();
        if(CollectionUtils.isEmpty(laborAttendDetails)){
            return "班次不能为空！";
        }
        String laborTime = laborRate.getLaborTime();
        String factory = laborRate.getFactoryName();
        if(StringUtils.isEmpty(laborTime)||StringUtils.isEmpty(factory)){
            return "参数异常！！";
        }
        if(this.getExistLaborByDateAndFactory(laborTime,factory) > 0){
            return "记录已经存在，无法新增！";
        }

        String id = CommonUtil.generateRandomNum("labor-");
        laborRate.setId(id);
        int count = laborRateMapper.insertSelective(laborRate);
        if (count < 1) {
            return "新增主表劳率失败！";
        }
        laborAttendRecord.setLaborId(id);
        String resp = laborAttendRecordService.addLaborAttendRecord(laborAttendRecord);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String validateLaborRate(QueryForm queryForm) throws Exception {
        String factoryName = queryForm.getFactoryName();
        String time = queryForm.getLaborTime();
        if(StringUtils.isEmpty(factoryName)||StringUtils.isEmpty(time)){
            return "参数异常！";
        }

        LaborRateExample example = new LaborRateExample();
        example.createCriteria().andFactoryNameEqualTo(factoryName).andLaborTimeEqualTo(time);
        int existCount = laborRateMapper.countByExample(example);
        if(existCount > 0){
            return "厂区："+factoryName+" 在时间："+time+"已经存在记录";
        }
        return "";
    }


    @Override
    public String updateLaborRate(LaborRate laborRate) throws Exception {
        String id = laborRate.getId();
        if(StringUtils.isEmpty(id)){
            return "缺少主键";
        }

        LaborAttendRecord laborAttendRecord = laborRate.getLaborAttendRecord();
        if(null == laborAttendRecord){
            return "参数异常！";
        }

        String resp = laborAttendRecordService.updateLaborAttendRecord(laborAttendRecord);
        if(StringUtils.isNotEmpty(resp)){
            throw new Exception(resp);
        }
        LaborRateExample example = new LaborRateExample();
        example.createCriteria().andIdEqualTo(id);
        int count = laborRateMapper.updateByExampleSelective(laborRate,example);
        if(count < 1){
            throw new Exception("更新失败！");
        }
        return CommonUtil.outStr(count);
    }

    @Override
    public String deleteLaborRateById(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return "缺少主键";
        }
        LaborRateExample example1 = new LaborRateExample();
        example1.createCriteria().andIdEqualTo(id).andStatusEqualTo(Constants.NORMAL_STATUS);
        List<LaborRate>laborRates = laborRateMapper.selectByExample(example1);
        if(CollectionUtils.isEmpty(laborRates)){
            return "删除的记录不存在";
        }
        LaborRate exist = laborRates.get(0);
        if(!StringUtils.equals("0",exist.getLabStatus())){
            return "状态不在编制中，无法删除";
        }
        LaborRate update = new LaborRate();
        update.setStatus(Constants.DEL_STATUS);
        LaborRateExample example = new LaborRateExample();
        example.createCriteria().andIdEqualTo(id);
        int count = laborRateMapper.updateByExampleSelective(update,example);
        return CommonUtil.outStr(count);
    }

    @Override
    public void exportLaborRate(QueryForm queryForm, HttpServletResponse response) throws Exception {
        Map<String,Object> result = Maps.newHashMap();
        String labTime = queryForm.getLaborTime();
        String factoryName = queryForm.getFactoryWorkshop();
        LaborRateExample example = new LaborRateExample();
        example.createCriteria().andFactoryNameEqualTo(factoryName).andLaborTimeLike(labTime+"-%").andStatusEqualTo(Constants.NORMAL_STATUS).andLabStatusEqualTo("1");
        example.setOrderByClause("labor_time asc");
        List<LaborRate> laborRates = laborRateMapper.selectByExample(example);

        String[] split = labTime.split("-");
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.YEAR, Integer.parseInt(split[0]));
        instance.set(Calendar.MONTH, Integer.parseInt(split[1])- 1);
        //一个月的多少天
        int actualMaximum = instance.getActualMaximum(Calendar.DAY_OF_MONTH);
        LaborRateExample example1 = new LaborRateExample();
        example1.createCriteria().andFactoryNameEqualTo(factoryName).andLaborTimeLike(labTime+"-%").andLaborResultEqualTo("0");
        //未达成的数量
        int notCount = laborRateMapper.countByExample(example1);
        LaborRateExample isExamples = new LaborRateExample();
        isExamples.createCriteria().andFactoryNameEqualTo(factoryName).andLaborTimeLike(labTime+"-%").andLaborResultEqualTo("1");
        //达成的数量
        int isCount = laborRateMapper.countByExample(isExamples);
        //达成率
        double rate = (double)isCount / actualMaximum;
        rate = Math.round(rate * 100.0 * 100) / 100.0;
        String rateStr = String.format("%.2f%%", rate);
        double rateDouble = Double.parseDouble(rateStr.replace("%", ""));

        result.put("laborTime", queryForm.getLaborTime());
        result.put("actualMaximum", actualMaximum);
        result.put("notCount", notCount);
        result.put("isCount", isCount);
        result.put("rate", rateDouble+"%");
        result.put("factoryName", queryForm.getFactoryWorkshop());
        result.put("laborRates", laborRates);
        String fileName = CommonUtil.generateRandomNum("ll-")+".xlsx";
        String filePath = config.filePath+fileName;
        String nameStr="劳率分析.xlsx";
        TemplateExcelUtils.downLoadExcel(filePath,nameStr,result,"llfx.xlsx", response);
    }

    @Override
    public Map<String, Object> getListByRateAnalysis(QueryForm queryForm) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        String factoryName = queryForm.getFactoryName();
        String laborTime = queryForm.getLaborTime();
        String[] split = laborTime.split("-");
        Calendar instance = Calendar.getInstance();
        instance.set(Calendar.YEAR, Integer.parseInt(split[0]));
        instance.set(Calendar.MONTH, Integer.parseInt(split[1])- 1);
        //一个月的多少天
        int actualMaximum = instance.getActualMaximum(Calendar.DAY_OF_MONTH);
        LaborRateExample example = new LaborRateExample();
        example.createCriteria().andFactoryNameEqualTo(factoryName).andLaborTimeLike(laborTime+"-%").andLaborResultEqualTo("0");
        //未达成的数量
        int notCount = laborRateMapper.countByExample(example);
        LaborRateExample isExamples = new LaborRateExample();
        isExamples.createCriteria().andFactoryNameEqualTo(factoryName).andLaborTimeLike(laborTime+"-%").andLaborResultEqualTo("1");
        //达成的数量
        int isCount = laborRateMapper.countByExample(isExamples);
        //达成率
        double result = (double)isCount / actualMaximum;
        result = Math.round(result * 100.0) / 100.0;
        map.put("factoryName",factoryName);
        map.put("laborTime",laborTime);
        map.put("actualMaximum",actualMaximum);
        map.put("notCount",notCount);
        map.put("isCount",isCount);
        map.put("result",result);
        return map;
    }


    private int getExistLaborByDateAndFactory(String time,String factory){
        LaborRate query = new LaborRate();
        query.setFactoryName(factory);
        query.setLaborTime(time);
        int existCount = laborRateMapper.selectLaborCountByDateAndFactory(query);
        return existCount;
    }

}
